package cn.iocoder.yudao.module.eval.service.major;

import cn.hutool.core.collection.CollUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.eval.controller.admin.major.vo.*;
import cn.iocoder.yudao.module.eval.dal.dataobject.major.MajorDO;
import cn.iocoder.yudao.module.eval.dal.dataobject.majorcategory.MajorCategoryDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.eval.dal.mysql.major.MajorMapper;
import cn.iocoder.yudao.module.eval.dal.mysql.majorcategory.MajorCategoryMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.yudao.module.eval.enums.ErrorCodeConstants.*;

/**
 * 专业管理 Service 实现类
 *
 * @author 龙头企业
 */
@Service
@Validated
public class MajorServiceImpl implements MajorService {

    @Resource
    private MajorMapper majorMapper;

    @Resource
    private MajorCategoryMapper majorCategoryMapper;

    @Override
    public Long createMajor(MajorSaveReqVO createReqVO) {
        // 插入
        MajorDO major = BeanUtils.toBean(createReqVO, MajorDO.class);
        // 显式设置deleted字段默认值
        major.setDeleted(false);
        majorMapper.insert(major);

        // 返回
        return major.getId();
    }

    @Override
    public void updateMajor(MajorSaveReqVO updateReqVO) {
        // 校验存在
        validateMajorExists(updateReqVO.getId());
        // 更新
        MajorDO updateObj = BeanUtils.toBean(updateReqVO, MajorDO.class);
        majorMapper.updateById(updateObj);
    }

    @Override
    public void deleteMajor(Long id) {
        // 校验存在
        validateMajorExists(id);
        // 删除
        majorMapper.deleteById(id);
    }

    @Override
        public void deleteMajorListByIds(List<Long> ids) {
        // 删除
        majorMapper.deleteByIds(ids);
        }


    private void validateMajorExists(Long id) {
        if (majorMapper.selectById(id) == null) {
            throw exception(MAJOR_NOT_EXISTS);
        }
    }

    @Override
    public MajorDO getMajor(Long id) {
        return majorMapper.selectById(id);
    }

    @Override
    public PageResult<MajorDO> getMajorPage(MajorPageReqVO pageReqVO) {
        return majorMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MajorImportRespVO importMajor(List<MajorImportExcelVO> importExcelVOs, Boolean updateSupport) {
        System.out.println("Starting importMajor with " + (importExcelVOs != null ? importExcelVOs.size() : 0) + " records");
        
        if (CollUtil.isEmpty(importExcelVOs)) {
            System.out.println("Import list is empty, throwing exception");
            throw exception(MAJOR_IMPORT_LIST_IS_EMPTY);
        }

        MajorImportRespVO respVO = MajorImportRespVO.builder()
                .createCount(0).updateCount(0).failures(new ArrayList<>()).build();

        // 遍历处理所有导入数据
        for (int i = 0; i < importExcelVOs.size(); i++) {
            MajorImportExcelVO vo = importExcelVOs.get(i);
            System.out.println("Processing record " + (i+1) + ": " + vo.getCode() + " - " + vo.getSubCategoryName());
            
            // 校验数据
            try {
                // 查找专业大类
                MajorCategoryDO majorCategory = null;
                if (vo.getCategoryCode() != null && !vo.getCategoryCode().isEmpty()) {
                    // 根据编码查询专业大类
                    majorCategory = majorCategoryMapper.selectOne(MajorCategoryDO::getCode, vo.getCategoryCode());
                    System.out.println("Found major category: " + (majorCategory != null ? majorCategory.getName() : "null"));
                }

                // 检查专业编码是否存在
                MajorDO existingMajor = majorMapper.selectByCode(vo.getCode());
                System.out.println("Existing major with code " + vo.getCode() + ": " + (existingMajor != null ? "found" : "not found"));
                
                // 根据是否存在专业编码和是否支持更新来决定操作
                if (existingMajor == null) {
                    // 新增
                    System.out.println("Creating new major: " + vo.getCode());
                    MajorDO major = new MajorDO();
                    major.setCode(vo.getCode());
                    major.setName(vo.getSubCategoryName()); // 使用子类名称作为专业名称
                    major.setLevel(vo.getSkillLevel()); // 使用技能等级作为等级
                    major.setTrainingObjective(vo.getTrainingGoal());
                    major.setStudyPeriod(vo.getStudyYear());
                    major.setVocationalCompetence(vo.getOccupationalAbility());
                    major.setCorrespondingOccupation(vo.getCorrespondingOccupation());
                    major.setCurriculumContent(vo.getMajorTeachingContent());
                    major.setUpperLevelCode(vo.getUpperMajorCode());
                    major.setNextLevelCode(vo.getNextLevelCode());
                    major.setQualificationSkillLevel(vo.getVocationalQualification());
                    // 如果找到了专业大类，设置关联ID
                    if (majorCategory != null) {
                        major.setMajorCategoryId(majorCategory.getId());
                    }
                    major.setStatus(1); // 默认启用
                    major.setDeleted(false); // 未删除
                    
                    // 调试输出所有字段值
                    System.out.println("Major fields before insert:");
                    System.out.println("  code: " + major.getCode());
                    System.out.println("  name: " + major.getName());
                    System.out.println("  level: " + major.getLevel());
                    System.out.println("  training_objective: " + major.getTrainingObjective());
                    System.out.println("  study_period: " + major.getStudyPeriod());
                    System.out.println("  vocational_competence: " + major.getVocationalCompetence());
                    System.out.println("  corresponding_occupation: " + major.getCorrespondingOccupation());
                    System.out.println("  curriculum_content: " + major.getCurriculumContent());
                    System.out.println("  upper_level_code: " + major.getUpperLevelCode());
                    System.out.println("  next_level_code: " + major.getNextLevelCode());
                    System.out.println("  qualification_skill_level: " + major.getQualificationSkillLevel());
                    System.out.println("  major_category_id: " + major.getMajorCategoryId());
                    System.out.println("  status: " + major.getStatus());
                    
                    majorMapper.insert(major);
                    respVO.setCreateCount(respVO.getCreateCount() + 1);
                    System.out.println("Created major with ID: " + major.getId());
                } else if (updateSupport) {
                    // 更新
                    System.out.println("Updating existing major: " + vo.getCode());
                    MajorDO major = new MajorDO();
                    major.setId(existingMajor.getId());
                    major.setCode(vo.getCode());
                    major.setName(vo.getSubCategoryName()); // 使用子类名称作为专业名称
                    major.setLevel(vo.getSkillLevel()); // 使用技能等级作为等级
                    major.setTrainingObjective(vo.getTrainingGoal());
                    major.setStudyPeriod(vo.getStudyYear());
                    major.setVocationalCompetence(vo.getOccupationalAbility());
                    major.setCorrespondingOccupation(vo.getCorrespondingOccupation());
                    major.setCurriculumContent(vo.getMajorTeachingContent());
                    major.setUpperLevelCode(vo.getUpperMajorCode());
                    major.setNextLevelCode(vo.getNextLevelCode());
                    major.setQualificationSkillLevel(vo.getVocationalQualification());
                    // 如果找到了专业大类，设置关联ID
                    if (majorCategory != null) {
                        major.setMajorCategoryId(majorCategory.getId());
                    }
                    
                    // 调试输出所有字段值
                    System.out.println("Major fields before update:");
                    System.out.println("  id: " + major.getId());
                    System.out.println("  code: " + major.getCode());
                    System.out.println("  name: " + major.getName());
                    System.out.println("  level: " + major.getLevel());
                    System.out.println("  training_objective: " + major.getTrainingObjective());
                    System.out.println("  study_period: " + major.getStudyPeriod());
                    System.out.println("  vocational_competence: " + major.getVocationalCompetence());
                    System.out.println("  corresponding_occupation: " + major.getCorrespondingOccupation());
                    System.out.println("  curriculum_content: " + major.getCurriculumContent());
                    System.out.println("  upper_level_code: " + major.getUpperLevelCode());
                    System.out.println("  next_level_code: " + major.getNextLevelCode());
                    System.out.println("  qualification_skill_level: " + major.getQualificationSkillLevel());
                    System.out.println("  major_category_id: " + major.getMajorCategoryId());
                    
                    majorMapper.updateById(major);
                    respVO.setUpdateCount(respVO.getUpdateCount() + 1);
                    System.out.println("Updated major with ID: " + major.getId());
                } else {
                    // 编码已存在但不支持更新，记录为失败
                    System.out.println("Major code already exists and update not supported: " + vo.getCode());
                    respVO.getFailures().add(MajorImportRespVO.MajorImportFailureVO.builder()
                            .rowIndex(i + 1)
                            .name(vo.getSubCategoryName())
                            .errorMsg("专业编码已存在")
                            .build());
                }
            } catch (Exception e) {
                // 记录导入失败
                System.out.println("Failed to process record " + (i+1) + ": " + e.getMessage());
                e.printStackTrace();
                respVO.getFailures().add(MajorImportRespVO.MajorImportFailureVO.builder()
                        .rowIndex(i + 1)
                        .name(vo.getSubCategoryName())
                        .errorMsg(e.getMessage())
                        .build());
            }
        }
        System.out.println("Import completed. Created: " + respVO.getCreateCount() + ", Updated: " + respVO.getUpdateCount() + ", Failures: " + respVO.getFailures().size());
        return respVO;
    }
}